package com.jiubanqingchen.future.common.tool;

import com.jfinal.kit.JsonKit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpSession;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint(value = "/webSocket.ws/{userid}")
public class WebSocketTool {
    private static Logger logger = LoggerFactory.getLogger(WebSocketTool.class);
    private static Map<String, WebSocketTool> clients = new ConcurrentHashMap<String, WebSocketTool>();
    private Session session;
    private String userid;

    @OnOpen
    public void onOpen(@PathParam("userid") String userid, Session session) throws IOException {
        this.userid = userid;
        this.session = session;
        clients.put(userid, this);
        logger.info(userid + "websocket 已连接");
    }

    @OnClose
    public void onClose() throws IOException {
        clients.remove(userid);
        logger.info("Websocket用户 " + userid + " 连接已关闭");
    }

    @OnMessage
    public void onMessage(String message) throws IOException {
        logger.info(message);
    }

    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
    }

    /**
     * @param @param  message 信息
     * @param @param  To userId
     * @param @throws IOException    参数
     * @return void    返回类型
     * @throws
     * @Title: sendMessageTo
     * @Description: (发送信息给某个人)
     * @author light_dust
     * @date 2019年10月21日 下午9:38:38
     */
    public static void sendMessageTo(Object message, String userId) throws IOException {
        for (WebSocketTool item : clients.values()) {
            if (item.userid.equals(userId))
                item.session.getAsyncRemote().sendText(JsonKit.toJson(message));
        }
    }

    public static void sendMessageTo(Object message, String[] userIds) throws IOException {
        if (userIds == null) return;
        for (String userId : userIds) sendMessageTo(message, userId);
    }

    /**
     * @param @param  message
     * @param @throws IOException    参数
     * @return void    返回类型
     * @throws
     * @Title: sendMessageAll
     * @Description: (给所有在线的websocket用户发送信息)
     * @author light_dust
     * @date 2019年10月21日 下午9:41:15
     */
    public static void sendMessageAll(Object message) throws IOException {
        for (WebSocketTool item : clients.values()) {
            item.session.getAsyncRemote().sendText(JsonKit.toJson(message));
        }
    }

    /**
     * 得到在线的用户id信息
     *
     * @return
     */
    public static List<String> getCurrentUserIds() {
        List<String> userIds = new ArrayList<>();
        for (String key : clients.keySet()) {
            userIds.add(key);
        }
        return userIds;
    }
}